package com.wish.datastructure.hashtable;

/**
 * Created by suliucheng on 2021/4/19 13:33
 * Directions:
 */
public class MyHashTable {
    /**
     * 初始数组给默认值 16
     */
    private int size = 16;
    /**
     * 链表数组
     */
    private StudentList[] studentLists = new StudentList[size];


    public MyHashTable() {
    }

    public MyHashTable(int size) {
        this.size = size;
        studentLists = new StudentList[size];
    }

    /**
     * 通过id查找数据
     * @param id
     * @return
     */
    public Student findById(int id) {
        StudentList list = studentLists[getIndex(id)];
        if (list == null) {
            throw new RuntimeException("该id的信息不存在于所要查找的hash表上");
        } else {
            return list.findById(id);
        }
    }

    /**
     * 向hashtable中新添加一个数据
     *
     * @param newStudent 学生信息
     * @return
     */
    public Student add(Student newStudent) {
        int index = getIndex(newStudent.getId());
        if (studentLists[index] == null) {
            StudentList temp = new StudentList();
            temp.add(newStudent);
            studentLists[index] = temp;
        } else {
            StudentList temp = studentLists[index];
            temp.add(newStudent);
        }
        return newStudent;
    }

    private int getIndex(int id) {
        return id % size;
    }

    /**
     * 遍历hash表
     */
    public void list() {
        for (int i = 0; i < size; i++) {
            if (studentLists[i] == null) {
                System.out.println("该链表为空");
            } else {
                studentLists[i].list();
                System.out.println();
            }
        }

    }
}
